<?php

//echo $mtDate = date('Y-m-d');
//exit;
require_once("libs/Authorize_new/authorize.class.php");
require_once ("libs/NMI/nmi.php"); 
//require_once("libs/Mijireh/Mijireh.php");
require_once("libs/FirstData/FirstData.php");
require_once("paypal/paypal.class.php");
require_once("libs/swift/swift_required.php");
require_once("libs/general_inc.php");

@session_start();

class Checkout extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {

	$paymentArray = $_SESSION['paymentArray'];
        $sql = new sql();
        $sql->connect();
        $serverreply = "";
        $GENOBJ = new generalFunction();
		$countryArray = array("" => 'Select',
"AF"=> 'Afghanistan',
"AX"=> 'Aland Islands',
"AL"=> 'Albania',
"DZ"=> 'Algeria',
"AS"=> 'American Samoa',
"AD"=> 'Andorra',
"AO"=> 'Angola',
"AI"=> 'Anguilla',
"AQ"=> 'Antarctica',
"AG"=> 'Antigua and Barbuda',
"AR"=> 'Argentina',
"AM"=> 'Armenia',
"AW"=> 'Aruba',
"AU"=> 'Australia',
"AT"=> 'Austria',
"AZ"=> 'Azerbaijan',
"BS"=> 'Bahamas',
"BH"=> 'Bahrain',
"BD"=> 'Bangladesh',
"BB"=> 'Barbados',
"BY"=> 'Belarus',
"BE"=> 'Belgium',
"BZ"=> 'Belize',
"BJ"=> 'Benin',
"BM"=> 'Bermuda',
"BT"=> 'Bhutan',
"BO"=> 'Bolivia, Plurinational State of',
"BQ"=> 'Bonaire, Sint Eustatius and Saba',
"BA"=> 'Bosnia and Herzegovina',
"BW"=> 'Botswana',
"BV"=> 'Bouvet Island',
"BR"=> 'Brazil',
"IO"=> 'British Indian Ocean Territory',
"BN"=> 'Brunei Darussalam',
"BG"=> 'Bulgaria',
"BF"=> 'Burkina Faso',
"BI"=> 'Burundi',
"KH"=> 'Cambodia',
"CM"=> 'Cameroon',
"CA"=> 'Canada',
"CV"=> 'Cape Verde',
"KY"=> 'Cayman Islands',
"CF"=> 'Central African Republic',
"TD"=> 'Chad',
"CL"=> 'Chile',
"CN"=> 'China',
"CX"=> 'Christmas Island',
"CC"=> 'Cocos (Keeling) Islands',
"CO"=> 'Colombia',
"KM"=> 'Comoros',
"CG"=> 'Congo',
"CD"=> 'Congo, the Democratic Republic of the',
"CK"=> 'Cook Islands',
"CR"=> 'Costa Rica',
"CI"=> 'Cote d"Ivoire',
"HR"=> 'Croatia',
"CU"=> 'Cuba',
"CW"=> 'Curacao',
"CY"=> 'Cyprus',
"CZ"=> 'Czech Republic',
"DK"=> 'Denmark',
"DJ"=> 'Djibouti',
"DM"=> 'Dominica',
"DO"=> 'Dominican Republic',
"EC"=> 'Ecuador',
"EG"=> 'Egypt',
"SV"=> 'El Salvador',
"GQ"=> 'Equatorial Guinea',
"ER"=> 'Eritrea',
"EE"=> 'Estonia',
"ET"=> 'Ethiopia',
"FK"=> 'Falkland Islands (Malvinas)',
"FO"=> 'Faroe Islands',
"FJ"=> 'Fiji',
"FI"=> 'Finland',
"FR"=> 'France',
"GF"=> 'French Guiana',
"PF"=> 'French Polynesia',
"TF"=> 'French Southern Territories',
"GA"=> 'Gabon',
"GM"=> 'Gambia',
"GE"=> 'Georgia',
"DE"=> 'Germany',
"GH"=> 'Ghana',
"GI"=> 'Gibraltar',
"GR"=> 'Greece',
"GL"=> 'Greenland',
"GD"=> 'Grenada',
"GP"=> 'Guadeloupe',
"GU"=> 'Guam',
"GT"=> 'Guatemala',
"GG"=> 'Guernsey',
"GN"=> 'Guinea',
"GW"=> 'Guinea-Bissau',
"GY"=> 'Guyana',
"HT"=> 'Haiti',
"HM"=> 'Heard Island and McDonald Islands',
"VA"=> 'Holy See (Vatican City State)',
"HN"=> 'Honduras',
"HK"=> 'Hong Kong',
"HU"=> 'Hungary',
"IS"=> 'Iceland',
"IN"=> 'India',
"ID"=> 'Indonesia',
"IR"=> 'Iran, Islamic Republic of',
"IQ"=> 'Iraq',
"IE"=> 'Ireland',
"IM"=> 'Isle of Man',
"IL"=> 'Israel',
"IT"=> 'Italy',
"JM"=> 'Jamaica',
"JP"=> 'Japan',
"JE"=> 'Jersey',
"JO"=> 'Jordan',
"KZ"=> 'Kazakhstan',
"KE"=> 'Kenya',
"KI"=> 'Kiribati',
"KP"=> 'Korea, Democratic People"s Republic of',
"KR"=> 'Korea, Republic of',
"KW"=> 'Kuwait',
"KG"=> 'Kyrgyzstan',
"LA"=> 'Lao People"s Democratic Republic',
"LV"=> 'Latvia',
"LB"=> 'Lebanon',
"LS"=> 'Lesotho',
"LR"=> 'Liberia',
"LY"=> 'Libya',
"LI"=> 'Liechtenstein',
"LT"=> 'Lithuania',
"LU"=> 'Luxembourg',
"MO"=> 'Macao',
"MK"=> 'Macedonia, the former Yugoslav Republic of',
"MG"=> 'Madagascar',
"MW"=> 'Malawi',
"MY"=> 'Malaysia',
"MV"=> 'Maldives',
"ML"=> 'Mali',
"MT"=> 'Malta',
"MH"=> 'Marshall Islands',
"MQ"=> 'Martinique',
"MR"=> 'Mauritania',
"MU"=> 'Mauritius',
"YT"=> 'Mayotte',
"MX"=> 'Mexico',
"FM"=> 'Micronesia, Federated States of',
"MD"=> 'Moldova, Republic of',
"MC"=> 'Monaco',
"MN"=> 'Mongolia',
"ME"=> 'Montenegro',
"MS"=> 'Montserrat',
"MA"=> 'Morocco',
"MZ"=> 'Mozambique',
"MM"=> 'Myanmar',
"NA"=> 'Namibia',
"NR"=> 'Nauru',
"NP"=> 'Nepal',
"NL"=> 'Netherlands',
"NC"=> 'New Caledonia',
"NZ"=> 'New Zealand',
"NI"=> 'Nicaragua',
"NE"=> 'Niger',
"NG"=> 'Nigeria',
"NU"=> 'Niue',
"NF"=> 'Norfolk Island',
"MP"=> 'Northern Mariana Islands',
"NO"=> 'Norway',
"OM"=> 'Oman',
"PK"=> 'Pakistan',
"PW"=> 'Palau',
"PS"=> 'Palestinian Territory, Occupied',
"PA"=> 'Panama',
"PG"=> 'Papua New Guinea',
"PY"=> 'Paraguay',
"PE"=> 'Peru',
"PH"=> 'Philippines',
"PN"=> 'Pitcairn',
"PL"=> 'Poland',
"PT"=> 'Portugal',
"PR"=> 'Puerto Rico',
"QA"=> 'Qatar',
"RE"=> 'Reunion',
"RO"=> 'Romania',
"RU"=> 'Russian Federation',
"RW"=> 'Rwanda',
"BL"=> 'Saint Barthelemy',
"SH"=> 'Saint Helena, Ascension and Tristan da Cunha',
"KN"=> 'Saint Kitts and Nevis',
"LC"=> 'Saint Lucia',
"MF"=> 'Saint Martin (French part)',
"PM"=> 'Saint Pierre and Miquelon',
"VC"=> 'Saint Vincent and the Grenadines',
"WS"=> 'Samoa',
"SM"=> 'San Marino',
"ST"=> 'Sao Tome and Principe',
"SA"=> 'Saudi Arabia',
"SN"=> 'Senegal',
"RS"=> 'Serbia',
"SC"=> 'Seychelles',
"SL"=> 'Sierra Leone',
"SG"=> 'Singapore',
"SX"=> 'Sint Maarten (Dutch part)',
"SK"=> 'Slovakia',
"SI"=> 'Slovenia',
"SB"=> 'Solomon Islands',
"SO"=> 'Somalia',
"ZA"=> 'South Africa',
"GS"=> 'South Georgia and the South Sandwich Islands',
"SS"=> 'South Sudan',
"ES"=> 'Spain',
"LK"=> 'Sri Lanka',
"SD"=> 'Sudan',
"SR"=> 'Suriname',
"SJ"=> 'Svalbard and Jan Mayen',
"SZ"=> 'Swaziland',
"SE"=> 'Sweden',
"CH"=> 'Switzerland',
"SY"=> 'Syrian Arab Republic',
"TW"=> 'Taiwan, Province of China',
"TJ"=> 'Tajikistan',
"TZ"=> 'Tanzania, United Republic of',
"TH"=> 'Thailand',
"TL"=> 'Timor-Leste',
"TG"=> 'Togo',
"TK"=> 'Tokelau',
"TO"=> 'Tonga',
"TT"=> 'Trinidad and Tobago',
"TN"=> 'Tunisia',
"TR"=> 'Turkey',
"TM"=> 'Turkmenistan',
"TC"=> 'Turks and Caicos Islands',
"TV"=> 'Tuvalu',
"UG"=> 'Uganda',
"UA"=> 'Ukraine',
"AE"=> 'United Arab Emirates',
"GB"=> 'United Kingdom',
"US"=> 'United States',
"UM"=> 'United States Minor Outlying Islands',
"UY"=> 'Uruguay',
"UZ"=> 'Uzbekistan',
"VU"=> 'Vanuatu',
"VE"=> 'Venezuela, Bolivarian Republic of',
"VN"=> 'Viet Nam',
"VG"=> 'Virgin Islands, British',
"VI"=> 'Virgin Islands, U.S.',
"WF"=> 'Wallis and Futuna',
"EH"=> 'Western Sahara',
"YE"=> 'Yemen',
"ZM"=> 'Zambia',
"ZW"=> 'Zimbabwe');
		
        if (count($_SESSION['shoping_cart']) == 0) {
            header("Location: " . URL . "product");
        }
        //check if final amount is less than zero then redirect to cart page
        $total_Amount_chk = 0;
        $Discount_price_chk = 0;
        foreach ($_SESSION['shoping_cart'] as $key => $value) {
            $total_Amount_chk += $value['prd_qty'] * $value['prd_price'];
        }
        $cat_match_qty = 1;
        
        if (isset($_SESSION['coupon_detail'])) {
            $Discount_price_chk = $_SESSION['coupon_detail']['coupon_price'];
            $Discount_code = $_SESSION['coupon_detail']['coupon_code'];
            $coupon_category = $_SESSION['coupon_detail']['coupon_category'];
            $coupon_product = $_SESSION['coupon_detail']['coupon_product'];
            $coupon_type = $_SESSION['coupon_detail']['coupon_type'];
            $coupon_applied = $_SESSION['coupon_detail']['coupon_applied'];
            if ($coupon_type == 'collection' && $coupon_applied == 'per_item') {
                $cat_match_qty = 0;
            }
            if ($coupon_type == 'specific_product' && $coupon_applied == 'per_item') {
                $cat_match_qty = 0;
            }
            $total_Amount = '';
            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                $total_Amount = $total_Amount + ($value['prd_qty'] * $value['prd_price']);

                if ($coupon_type == 'collection' && $coupon_applied == 'per_item') {
                    if ($value['prd_cat_id'] == $coupon_category) {
                        $cat_match_qty += $value['prd_qty'];
                    }
                }
                if ($coupon_type == 'specific_product' && $coupon_applied == 'per_item') {
                    if ($value['prd_id'] == $coupon_product) {
                        $cat_match_qty += $value['prd_qty'];
                    }
                }
            }
        }




        $Final_amount_with_discount = $total_Amount_chk - ($Discount_price_chk * $cat_match_qty);
        if ($Final_amount_with_discount <= 0) {
            header("Location: " . URL . "cart");
        }

        if ($Final_amount_with_discount <= 0 && (isset($_SESSION['coupon_detail']) && $_SESSION['coupon_detail']['coupon_staus'] == 'invalid')) {
            header("Location: " . URL . "cart");
        }



        $errorArray = Array();
        //$this->view->ErrorMessage = '';

        $salutation = '';
        $fname = '';
        $lname = '';
        $email = '';
        $zipcode = '';
        $address = '';
        $state = '';
        $city = '';
        $phone = '';
        $country = '';
        $ag_name = '';
        $terms = '';
        $drpgateway = '';
        $payment_option = '';
        $drpCardType = '';
        $txtCreditcardno = '';
        $drpExpMonth = '';
        $expyear = '';
        $nameoncard = '';
        $cvv = '';
		$Discount_code = '';
		$codex ='';
		$securityerror = 0; 
            
            
        if (@$_POST['fname']) {

       
            function ValidEmailAddress($EmailAddress) {
                if (!preg_match("/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i", $EmailAddress)) {
                    return false;
                }
                return true;
            }
            
            function isNumeric($n) {
                if (!preg_match("/^[0-9]+$/", $n)) {
                    return false;
                }
                return true;
            }

            $salutation = $_POST['salutation'];
            $fname = $_POST['fname'];
            $lname = $_POST['lname'];
            $email = $_POST['email'];
            $zipcode = $_POST['zipcode'];
            $address = $_POST['address'];
            $state = $_POST['state'];
            $city = $_POST['city'];
            $ag_name = $_POST['ag_name'];
            $phone = $_POST['phone'];
            $country = $_POST['country'];
            $agent_id = trim($_POST['ag_name']);
            $drpgateway = $_POST['drpgateway'];
			$codex = $_POST['codex'];
			$securityerror = 0;
            
            if($_POST['drpgateway'] != 'Paypal'){
                $payment_option = $_POST['payment_optn'];
               // $drpCardType = $_POST['drpCardType'];
                $txtCreditcardno = $_POST['txtCreditcardno'];
                $drpExpMonth = $_POST['drpExpMonth'];
                $expyear = $_POST['expyear'];
                $nameoncard = $_POST['nameoncard'];
                $cvv = $_POST['cvv'];
            }
            
            
            
            if (array_key_exists('terms', $_POST)) {
                $terms = $_POST['terms'];
            }

            if (trim($_POST['salutation']) == "") {
                $errorArray[] = 'Please select salutation';
            }

            if (trim($_POST['fname']) == "") {
                $errorArray[] = 'Please enter firstname';
            }

            if (trim($_POST['lname']) == "") {
                $errorArray[] = 'Please enter lastname';
            }

            if (trim($_POST['email']) == "") {
                $errorArray[] = 'Please enter email';
            }

            if (!ValidEmailAddress($_POST['email'])) {
                $errorArray[] = 'Please enter valid email';
            }

            if (trim($_POST['zipcode']) == "") {
                $errorArray[] = 'Please enter zipcode';
            }

            if (trim($_POST['address']) == "") {
                $errorArray[] = 'Please enter address';
            }

            if (trim($_POST['state']) == "") {
                $errorArray[] = 'Please enter state';
            }

            if (trim($_POST['city']) == "") {
                $errorArray[] = 'Please enter city';
            }

            if (trim($_POST['phone']) == "") {
                $errorArray[] = 'Please enter phone no.';
            }

            if (trim($_POST['country']) == "") {
                $errorArray[] = 'Please select country';
            }
            if (trim($terms) == "") {
                $errorArray[] = 'Please select terms and conditions';
            }

            if (trim($_POST['drpgateway']) == "credit_card") {
               
                if (trim($payment_option) == "") {
                    $errorArray[] = 'Please select payment method';
                }
				if($_POST['codex'] != $_SESSION['security_code']){
					$securityerror = 1;
					$errorArray[] = 'Invalid Security code';
				}
				/* if (trim($drpCardType) == "") {
                    $errorArray[] = 'Please select card type';
                }*/
                if (trim($payment_option) == "") {
                    $errorArray[] = 'Please select payment method';
                }
                if (trim($txtCreditcardno) == "") {
                    $errorArray[] = 'Please enter credit number';
                }
                if (trim($txtCreditcardno) != "" && !isNumeric($txtCreditcardno)) {
                    $errorArray[] = 'Please enter valid credit number';
                }
                if (trim($drpExpMonth) == "") {
                    $errorArray[] = 'Please select month';
                }
                if (trim($expyear) == "") {
                    $errorArray[] = 'Please select year';
                }
				if(trim($drpExpMonth) < date('m')  && trim($expyear) == date('Y') ){
                    $errorArray[] = 'Please select valid date';
                }
                if (trim($nameoncard) == "") {
                    $errorArray[] = 'Please enter name on card';
                }
                if (trim($cvv) == "") {
                    $errorArray[] = 'Please enter cvv number';
                }
                
            }



            if (count($errorArray) > 0) {
                
            } else {
                $total_Amount = 0;
                $Discount_price = 0;
                $cat_match_count = 1;
                $cat_match_qty = 1;
                $coupon_applied = '';
                $coupon_product = '';
                $coupon_category = '';
                if (isset($_SESSION['coupon_detail'])) {
                    $Discount_price = $_SESSION['coupon_detail']['coupon_price'];
                    $Discount_code = $_SESSION['coupon_detail']['coupon_code'];
                    if ($_SESSION['coupon_detail']['coupon_applied'] == 'per_item') {
                        $cat_match_count = 0;
                        $cat_match_qty = 0;
                        $coupon_applied = 'per_item';
                        $coupon_category = $_SESSION['coupon_detail']['coupon_category'];
                        $coupon_product = $_SESSION['coupon_detail']['coupon_product'];
                    }
                }

                foreach ($_SESSION['shoping_cart'] as $key => $value) {
                    $total_Amount += $value['prd_qty'] * $value['prd_price'];
                    if (($value['prd_cat_id'] == $coupon_category) && $coupon_applied == 'per_item') {
                        $cat_match_count +=1;
                        $cat_match_qty += $value['prd_qty'];
                    }
                    if (($value['prd_id'] == $coupon_product) && ($coupon_applied == 'per_item')) {
                        $cat_match_count +=1;
                        $cat_match_qty += $value['prd_qty'];
                    }
                }





                $Final_amount_with_discount = $total_Amount - ($Discount_price * $cat_match_qty);


                //$UserArray = $sql->fetch("tbl_user", array("user_email" => $_POST['email']));
                
                $arraydata = array("user_prefix" => $_POST['salutation'],
                        "user_firstname" => $_POST['fname'],
                        "user_lastname" => $_POST['lname'],
                        "user_email" => $_POST['email'],
                        "user_zipcode" => $_POST['zipcode'],
                        "user_address" => $_POST['address'],
                        "user_state" => $_POST['state'],
                        "user_city" => $_POST['city'],
                        "user_phoneno" => $_POST['phone'],
                        "user_country" => $_POST['country'],
                        "user_createdate" => date('Y-m-d h:i:s'),
                        "user_status" => 1,
                        "user_terms" => $_POST['terms']
                    );
                
                $filterArray = Array("TrimElement", "htmlEntity");  
                $filterElements = $GENOBJ->filter($arraydata, $filterArray);
                
                $_SESSION['CHECKOUT_DATA'] = $filterElements;
                $_SESSION['CHECKOUT_DATA']['createDate'] = date('Y-m-d H:i:s');
                $_SESSION['CHECKOUT_DATA']['payment_gateway'] = strtolower($drpgateway);
                $_SESSION['CHECKOUT_DATA']['payment_method'] = $payment_option;
                
				//echo '1';
                include('quickbooks/add_customer.php');
                              
                //echo '2';
                //add product in quickbook 
                include('quickbooks/addproduct.php');
				//echo '3';
                
				//exit;
                $_SESSION['CHECKOUT_DATA']['shopping_cart'] = $_SESSION['shoping_cart'];
                if(isset($_SESSION['coupon_detail'])){
                    $_SESSION['CHECKOUT_DATA']['coupon_detail'] = $_SESSION['coupon_detail'];
                }
                $pt_type = "";
                $payment_type = '';

                //get customer data from session
                $UserArray = $_SESSION['CHECKOUT_DATA'];
                $last_quickbook_id = $UserArray['qb_customer_id'];
                $user_firstname = $UserArray['user_firstname'];
                $user_email = $UserArray['user_email'];

               
                //Paypal Payment
                if (@$_POST['drpgateway'] == 'Paypal') {
                    $CANCEL_URL = URL . "checkout?dn_id=1";
                    $RETURN_URL = URL . "thankyou/paypal/" . trim($_POST['payment_optn']) . "/" . trim($_POST['ag_name']);

                    $paypalPaymentArray = Array();
                    $paypalPaymentArray['dn_firstname'] = $fname;
                    $paypalPaymentArray['dn_lastname'] = $lname;
                    $paypalPaymentArray['dn_address'] = $address;
                    $paypalPaymentArray['dn_city'] = $city;
                    $paypalPaymentArray['dn_state'] = $state;
                    $paypalPaymentArray['dn_country'] = $country;
                    $paypalPaymentArray['dn_zipcode'] = $zipcode;
                    $paypalPaymentArray['dn_email'] = $email;
                    $paypalPaymentArray['dn_phone'] = $phone;


                    $paypalmode = (PAYPAL_MODE == 'sandbox') ? '.sandbox' : '';

                    $total_Amount_pay = 0;
                    $ItemName = '';
                    $ItemPrice = '';
                    $ItemDesc = '';
                    $ItemQty = '';
                    $ItemTotalPrice = '';
                    $i = 1;
                    $parmsString = '';
                    $j = 0;
                    foreach ($_SESSION['shoping_cart'] as $s_key => $s_value) {
                        $total_Amount_pay += $s_value['prd_qty'] * $s_value['prd_price'];
                        $ItemName = $s_value['prd_name'];
                        $ItemPrice = $s_value['prd_price'];
                        $ItemDesc = $s_value['prd_desc'];
                        $ItemQty = $s_value['prd_qty'];
                        $ItemTotalPrice = $ItemPrice * $ItemQty;
                        $parmsString .= '&L_PAYMENTREQUEST_0_NAME' . $j . '=' . urlencode($ItemName) .
                                //'&L_PAYMENTREQUEST_0_DESC'.$j.'=' . urlencode($ItemDesc) .
                                '&L_PAYMENTREQUEST_0_AMT' . $j . '=' . urlencode($ItemPrice) .
                                '&L_PAYMENTREQUEST_0_QTY' . $j . '=' . urlencode($ItemQty);
                        $j++;
                        $i++;
                    }
                    $discountString = '';
                    $no_discount_code = $j;
                    $discountTotalPrice = 0;

                    if (isset($_SESSION['coupon_detail'])) {
                        $discountName = "Discount Code - " . $_SESSION['coupon_detail']['coupon_code'];
                        $discountPrice = "-" . $_SESSION['coupon_detail']['coupon_price']; //Item Price
                        $discountDescription = $_SESSION['coupon_detail']['coupon_code'];
                        $discountQty = $cat_match_qty; // Item Quantity
                        $discountTotalPrice = $discountPrice * $discountQty;
                        $discountString = '&L_PAYMENTREQUEST_0_NAME' . $no_discount_code . '=' . urlencode($discountName) .
                                //'&L_PAYMENTREQUEST_0_DESC'.$no_discount_code.'=' . urlencode($discountDescription) .
                                '&L_PAYMENTREQUEST_0_AMT' . $no_discount_code . '=' . urlencode($discountPrice) .
                                '&L_PAYMENTREQUEST_0_QTY' . $no_discount_code . '=' . urlencode($discountQty);
                    }
                    $GrandTotal = $total_Amount_pay + $discountTotalPrice;

                    //Parameters for SetExpressCheckout, which will be sent to PayPal
                    $padata = '&METHOD=SetExpressCheckout' .
                            '&RETURNURL=' . urlencode($RETURN_URL) .
                            '&CANCELURL=' . urlencode($CANCEL_URL) .
                            '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") .
                            $parmsString .
                            //Discount 
                            $discountString .
                            '&SOLUTIONTYPE=Sole' .
                            '&LANDINGPAGE=Billing' .
                            '&PAYMENTREQUEST_0_SHIPTONAME=' . $paypalPaymentArray['dn_firstname'] . " " . $paypalPaymentArray['dn_lastname'] .
                            '&PAYMENTREQUEST_0_SHIPTOSTREET=' . $paypalPaymentArray['dn_address'] .
                            '&PAYMENTREQUEST_0_SHIPTOCITY=' . $paypalPaymentArray['dn_city'] .
                            '&PAYMENTREQUEST_0_SHIPTOSTATE=' . $paypalPaymentArray['dn_state'] .
                            '&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=' . $paypalPaymentArray['dn_country'] .
                            '&PAYMENTREQUEST_0_SHIPTOZIP=' . $paypalPaymentArray['dn_zipcode'] .
                            '&EMAIL=' . $paypalPaymentArray['dn_email'] .
                            '&PAYMENTREQUEST_0_SHIPTOPHONENUM=' . $paypalPaymentArray['dn_phone'] .
                            '&NOSHIPPING=1' .
                            '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) .
                            '&ALLOWNOTE=1';

                    //We need to execute the "SetExpressCheckOut" method to obtain paypal token
                    $paypal = new MyPayPal();
                    $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, PAYPAL_API_USERNAME, PAYPAL_API_PASSWORD, PAYPAL_API_SIGNATURE, PAYPAL_MODE);
                    
                    
                    //Respond according to message we receive from Paypal
                    if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {

                        //Redirect user to PayPal store with Token received.
                        $paypalurl = 'https://www' . $paypalmode . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $httpParsedResponseAr["TOKEN"] . '';
                        header('Location: ' . $paypalurl);
                    } else {
                        //Show error message
                       header("Location: " . URL . "payment_error");
                     //   echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                    }
                }
                
                // CreditCard Payment
                if (@$_POST['drpgateway'] == 'credit_card') {
				/*	$name_define  = explode(" ",$nameoncard);
                    if(count($name_define) != 0){
                        $firstname = $name_define[0];
                        $lastname = $name_define[1];
                    }else{
                        $firstname = $nameoncard;
                        $lastname = '';
                    }
					
					*/
					$nameCardArray = explode( " " , $nameoncard);
					if ( count($nameCardArray) > 0 ) {
						$firstname = $nameCardArray['0'];
						if (count($nameCardArray) == 2) {
							$lastname = " ".$nameCardArray['1'];
						}
						if (count($nameCardArray) > 2) {
							unset($nameCardArray['0']);
							$lastname = " ". implode(" ", $nameCardArray);
						}
					}else{
						$firstname = $nameoncard;
                        $lastname = '';
					}
					


					if($payment_option == 'authorize'){
                        
                        $authorizeObj = new MyAuthorize();
                        $TransactionLoginsertId = 0;
                        $authorizeObj->settrasnsaction_url(AUTHORIZE_TRANSACTION_URL);
                        $authiorize_post_values = array(
                        // the API Login ID and Transaction Key must be replaced with valid values
                        "x_login" => AUTHORIZENET_API_LOGIN_ID,
                        "x_tran_key" => AUTHORIZENET_TRANSACTION_KEY,
                        "x_version" => "3.1",
                        "x_delim_data" => "TRUE",
                        "x_delim_char" => "|",
                        "x_relay_response" => "FALSE",
                        "x_currency_code" => "USD",
                        "x_type" => "AUTH_CAPTURE",
                        "x_method" => "CC",
                        "x_card_num" => $txtCreditcardno,
                        "x_exp_date" => $drpExpMonth.$expyear,
                        "x_amount" => $Final_amount_with_discount,
                        "x_first_name" => $firstname,
                        "x_last_name" => $lastname,
                        "x_address" => $address,
                        "x_city" => $city,
                        "x_state" => $state,
                        "x_zip" => $zipcode,
                        "x_country" => $country,
                        "x_email" => $email,
                    );

                    $authorizeResponse = $authorizeObj->callAimApi($authiorize_post_values);
                    /*
                        $sale = new AuthorizeNetAIM; 
                        $sale->amount = $Final_amount_with_discount; 
                        $sale->card_num = $txtCreditcardno; 
                        $sale->exp_date = $drpExpMonth."/".$expyear;
                        $sale->first_name = $fname; 
                        $sale->last_name = $lname; 
                        $sale->email = $email;
                        $sale->address = $address;
                        $sale->state = $state;
                        $sale->city = $city;
                        $sale->phone = $phone;
                        $sale->country = $country;
                        $sale->zip = $zipcode;
                        $response = $sale->authorizeAndCapture();
                        */
						
						$_SESSION['PAYMENT_ERROR'][$payment_option]['CODE'] = $authorizeResponse['2'];
						
						$_SESSION['PAYMENT_ERROR'][$payment_option]['MESSAGE'] = $authorizeResponse['3'];
						
					
                        if ($authorizeResponse['0'] == '1' ) { 
                            $orderNum = $authorizeResponse['6'];//$response->transaction_id;
                            $transaction_id = "Authorize - " . $orderNum;
                           //$transaction_id = $response->transaction_id; 
                            $paymentdata = array(
                                "pt_type" => 'credit_visa',
                                "pt_store" => 'authorize',
                                //"pt_user_id" => $lastid,
                                "pt_coupon_code" => $Discount_code,
                                "pt_coupon_price" => $Discount_price,
                                "pt_coupon_qty" => $cat_match_qty,
                                "pt_amt_without_cp" => $total_Amount,
                                "pt_transaction_id" => $orderNum,
                                "pt_agent_id" => $agent_id,
                                "pt_total_amount" => $Final_amount_with_discount,
                                "pt_createDate" => date('Y-m-d h:i:s'),
                                "pt_status" => 'active',
                            );
                            $filterArray = Array("TrimElement", "htmlEntity");  
                            $filterElements_payment = $GENOBJ->filter($paymentdata, $filterArray);
                            $sql->insert('payment_order', $filterElements_payment);
                            $lastpaymentid = $sql->last_id();
                            $responsedata = array(
                                "pr_pt_id" => $lastpaymentid,
                                "pr_response" => serialize($authorizeResponse),
                                "pr_createdate" => date('Y-m-d h:i:s'),
                                "pr_status" => 'active',
                            );
                            $filterElements_response = $GENOBJ->filter($responsedata, $filterArray);
                            
                            $sql->insert('tbl_payment_response', $filterElements_response);
                            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                            $orderdata = array(
                                //"or_user_id" => $lastid,
                                "or_product_id" => $value['prd_id'],
                                "payment_ref_id" => $lastpaymentid,
                                "or_prd_qty" => $value['prd_qty'],
                                "or_prd_price" => $value['prd_price'],
                                "or_price" => $value['prd_qty'] * $value['prd_price'],
                                "or_createdate" => date('Y-m-d h:i:s'),
                                "or_status" => 1,
                            );
                            $filterElements_order = $GENOBJ->filter($orderdata, $filterArray);
                           //  $sql->insert('tbl_payment_response', $filterElements_response);
                            $insert_order = $sql->insert('tbl_order', $filterElements_order);
                            $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
                            $key = $keyArray['mtd_value'];

                            if ($key == count($paymentArray)) {
                                $updatedKey = 1;
                            } else {
                                $updatedKey = $key + 1;
                            }

                            $update = $sql->update('tbl_metadata', array("mtd_value" => $updatedKey), array("mtd_key" => 'payment_key'));
                        }
                            include('quickbooks/salerecepit.php');
                        } else{
                            header("Location: " . URL . "payment_error");
                        }
                    }
                    if(trim($payment_option) == 'authorize1'){
                        //$sale = new AuthorizeNetAIM; 
                        $authorizeObj = new MyAuthorize();
                        $TransactionLoginsertId = 0;
                        $authorizeObj->settrasnsaction_url(AUTHORIZE_TRANSACTION_URL2);
                        $authiorize_post_values = array(
                        // the API Login ID and Transaction Key must be replaced with valid values
                        "x_login" => AUTHORIZENET_API_LOGIN_ID2,
                        "x_tran_key" => AUTHORIZENET_TRANSACTION_KEY2,
                        "x_version" => "3.1",
                        "x_delim_data" => "TRUE",
                        "x_delim_char" => "|",
                        "x_relay_response" => "FALSE",
                        "x_currency_code" => "USD",
                        "x_type" => "AUTH_CAPTURE",
                        "x_method" => "CC",
                        "x_card_num" => $txtCreditcardno,
                        "x_exp_date" => $drpExpMonth.$expyear,
                        "x_amount" => $Final_amount_with_discount,
                        "x_first_name" => $firstname,
                        "x_last_name" => $lastname,
                        "x_address" => $address,
                        "x_city" => $city,
                        "x_state" => $state,
                        "x_zip" => $zipcode,
                        "x_country" => $country,
                        "x_email" => $email,
                    );

                    $authorizeResponse = $authorizeObj->callAimApi($authiorize_post_values);
					
					
					
					
					$_SESSION['PAYMENT_ERROR'][$payment_option]['CODE'] = $authorizeResponse['2'];
						
					$_SESSION['PAYMENT_ERROR'][$payment_option]['MESSAGE'] = $authorizeResponse['3'];
					
						
                        if ($authorizeResponse['0'] == '1' ) { 
                            $orderNum = $authorizeResponse['6'];//$response->transaction_id;
                            $transaction_id = "Authorize - " . $orderNum;
                           //$transaction_id = $response->transaction_id; 
                            $paymentdata = array(
                                "pt_type" => 'credit_visa',
                                "pt_store" => 'authorize',
                                //"pt_user_id" => $lastid,
                                "pt_coupon_code" => $Discount_code,
                                "pt_coupon_price" => $Discount_price,
                                "pt_coupon_qty" => $cat_match_qty,
                                "pt_amt_without_cp" => $total_Amount,
                                "pt_transaction_id" => $orderNum,
                                "pt_agent_id" => $agent_id,
                                "pt_total_amount" => $Final_amount_with_discount,
                                "pt_createDate" => date('Y-m-d h:i:s'),
                                "pt_status" => 'active',
                            );
                            $filterArray = Array("TrimElement", "htmlEntity");  
                            $filterElements_payment = $GENOBJ->filter($paymentdata, $filterArray);
                            $sql->insert('payment_order', $filterElements_payment);
                            $lastpaymentid = $sql->last_id();
                            $responsedata = array(
                                "pr_pt_id" => $lastpaymentid,
                                "pr_response" => serialize($authorizeResponse),
                                "pr_createdate" => date('Y-m-d h:i:s'),
                                "pr_status" => 'active',
                            );
                            $filterElements_response = $GENOBJ->filter($responsedata, $filterArray);
                            
                            $sql->insert('tbl_payment_response', $filterElements_response);
                            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                            $orderdata = array(
                                //"or_user_id" => $lastid,
                                "or_product_id" => $value['prd_id'],
                                "payment_ref_id" => $lastpaymentid,
                                "or_prd_qty" => $value['prd_qty'],
                                "or_prd_price" => $value['prd_price'],
                                "or_price" => $value['prd_qty'] * $value['prd_price'],
                                "or_createdate" => date('Y-m-d h:i:s'),
                                "or_status" => 1,
                            );
                            $filterElements_order = $GENOBJ->filter($orderdata, $filterArray);
                           //  $sql->insert('tbl_payment_response', $filterElements_response);
                            $insert_order = $sql->insert('tbl_order', $filterElements_order);
                            $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
                            $key = $keyArray['mtd_value'];

                            if ($key == count($paymentArray)) {
                                $updatedKey = 1;
                            } else {
                                $updatedKey = $key + 1;
                            }

                            $update = $sql->update('tbl_metadata', array("mtd_value" => $updatedKey), array("mtd_key" => 'payment_key'));
                        }
                            include('quickbooks/salerecepit.php');
                        } else{
                            header("Location: " . URL . "payment_error");
                        }
                    }
                             
				  if($payment_option == 'nmi'){
                        $gw = new gwapi;
                        $username = USERNAME_NMI; 
                        $password = PASSWORD_NMI;
                        $gw->setLogin($username, $password);
                        $orderid = rand(100,1000);
                        
                        $gw->setBilling($firstname,$lastname,$address, $city, $state, $zipcode,
                        $country,$phone, $email);
                        $gw->setShipping($firstname, $lastname, $address,$city,
                                $state,$zipcode,$country,$email);
                        $gw->setOrder($orderid);
                        $r = $gw->doSale($Final_amount_with_discount, $txtCreditcardno, $drpExpMonth.$expyear, $cvv);
                        
						
						$_SESSION['PAYMENT_ERROR'][$payment_option]['CODE'] = $gw->responses['response_code'];
						
						$_SESSION['PAYMENT_ERROR'][$payment_option]['MESSAGE'] = $gw->responses['responsetext'];
						
                        
                        if($gw->responses['responsetext'] == 'SUCCESS'){
                            $orderNum = $gw->responses['transactionid'];
                            $transaction_id = "NMI - " . $orderNum;
                           //$transaction_id = $response->transaction_id; 
                            $paymentdata = array(
                                "pt_type" => 'credit_visa',
                                "pt_store" => 'Nmi',
                               // "pt_user_id" => $lastid,
                                "pt_coupon_code" => $Discount_code,
                                "pt_coupon_price" => $Discount_price,
                                "pt_coupon_qty" => $cat_match_qty,
                                "pt_amt_without_cp" => $total_Amount,
                                "pt_transaction_id" => $orderNum,
                                "pt_agent_id" => $agent_id,
                                "pt_total_amount" => $Final_amount_with_discount,
                                "pt_createDate" => date('Y-m-d h:i:s'),
                                "pt_status" => 'active',
                            );
                            $filterArray = Array("TrimElement", "htmlEntity");  
                            $filterElements_payment = $GENOBJ->filter($paymentdata, $filterArray);
                            $sql->insert('payment_order', $filterElements_payment);
                            $lastpaymentid = $sql->last_id();

                            $responsedata = array(
                                "pr_pt_id" => $lastpaymentid,
                                "pr_response" => serialize($gw->responses),
                                "pr_createdate" => date('Y-m-d h:i:s'),
                                "pr_status" => 'active',
                            );
                            $filterElements_response = $GENOBJ->filter($responsedata, $filterArray);
                            $sql->insert('tbl_payment_response', $filterElements_response);
                            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                            $orderdata = array(
                                //"or_user_id" => $lastid,
                                "or_product_id" => $value['prd_id'],
                                "payment_ref_id" => $lastpaymentid,
                                "or_prd_qty" => $value['prd_qty'],
                                "or_prd_price" => $value['prd_price'],
                                "or_price" => $value['prd_qty'] * $value['prd_price'],
                                "or_createdate" => date('Y-m-d h:i:s'),
                                "or_status" => 1,
                            );
                            $filterElements_order = $GENOBJ->filter($orderdata, $filterArray);
                            $insert_order = $sql->insert('tbl_order', $filterElements_order);
                            $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
                            $key = $keyArray['mtd_value'];

                            if ($key == count($paymentArray)) {
                                $updatedKey = 1;
                            } else {
                                $updatedKey = $key + 1;
                            }

                            $update = $sql->update('tbl_metadata', array("mtd_value" => $updatedKey), array("mtd_key" => 'payment_key'));
                        }
                            include('quickbooks/salerecepit.php');
                        }
                        else{
                            header("Location: " . URL . "payment_error/".$lastid);
                        }
                        
                    }
                  if($payment_option == 'first-data'){
                        $firstData = new FirstData(FD_GATEWAY_ID, FD_PASSWORD, FD_STATUS);
                        $firstData->setTransactionType(FirstData::TRAN_PURCHASE);
                        $firstData
								//->setCreditCardType($payment_option)
                                ->setCreditCardNumber($txtCreditcardno)
                                ->setCreditCardName($nameoncard)
                                ->setCreditCardExpiration($drpExpMonth.str_replace("20","",$expyear))
                                ->setAmount($Final_amount_with_discount)
                                ->setReferenceNumber(rand(100,999));

                        $response = $firstData->process();
						$response_decode = json_decode($response);
                     
						$_SESSION['PAYMENT_ERROR'][$payment_option]['CODE'] = $response_decode->bank_resp_code;
						
						$_SESSION['PAYMENT_ERROR'][$payment_option]['MESSAGE'] = $response_decode->bank_message;
						
						
						
						if ($firstData->isError()) {
                            // there was an error
                             header("Location: " . URL . "payment_error/".$lastid);
                        } else {
                            // transaction passed
                            $orderNum = $response_decode->transaction_tag;
                            $transaction_id = "FirstData - " . $orderNum;
                           //$transaction_id = $response->transaction_id; 
                            $paymentdata = array(
                                "pt_type" => 'credit_visa',
                                "pt_store" => 'FirstData',
                               // "pt_user_id" => $lastid,
                                "pt_coupon_code" => $Discount_code,
                                "pt_coupon_price" => $Discount_price,
                                "pt_coupon_qty" => $cat_match_qty,
                                "pt_amt_without_cp" => $total_Amount,
                                "pt_transaction_id" => $orderNum,
                                "pt_agent_id" => $agent_id,
                                "pt_total_amount" => $Final_amount_with_discount,
                                "pt_createDate" => date('Y-m-d h:i:s'),
                                "pt_status" => 'active',
                            );
                            $filterArray = Array("TrimElement", "htmlEntity");  
                            $filterElements_payment = $GENOBJ->filter($paymentdata, $filterArray);
                            
                            $sql->insert('payment_order', $filterElements_payment);
                            $lastpaymentid = $sql->last_id();


                            $responsedata = array(
                                "pr_pt_id" => $lastpaymentid,
                                "pr_response" => serialize($response_decode),
                                "pr_createdate" => date('Y-m-d h:i:s'),
                                "pr_status" => 'active',
                            );
                            $sql->insert('tbl_payment_response', $responsedata);
                            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                            $orderdata = array(
                                //"or_user_id" => $lastid,
                                "or_product_id" => $value['prd_id'],
                                "payment_ref_id" => $lastpaymentid,
                                "or_prd_qty" => $value['prd_qty'],
                                "or_prd_price" => $value['prd_price'],
                                "or_price" => $value['prd_qty'] * $value['prd_price'],
                                "or_createdate" => date('Y-m-d h:i:s'),
                                "or_status" => 1,
                            );
                            $filterElements_order = $GENOBJ->filter($orderdata, $filterArray);
                            $insert_order = $sql->insert('tbl_order', $filterElements_order);
                            $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
                            $key = $keyArray['mtd_value'];

                            if ($key == count($paymentArray)) {
                                $updatedKey = 1;
                            } else {
                                $updatedKey = $key + 1;
                            }

                            $update = $sql->update('tbl_metadata', array("mtd_value" => $updatedKey), array("mtd_key" => 'payment_key'));
                        }
                            include('quickbooks/salerecepit.php');
                        }
                        
                        
                        
                    }
                }
            }
        }


        //Fetch the Current Key
        $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
        $key = $keyArray['mtd_value'];

        $updatedPaymentArray = array();
        foreach ($paymentArray as $p_key => $p_value) {
            $updatedPaymentArray[$p_key]['name'] = $p_value['name'];
            $updatedPaymentArray[$p_key]['key'] = $p_value['key'];
        }

        for ($i = $key + 1; $i <= count($paymentArray); $i++) {
            $paymentstore[$i] = $updatedPaymentArray[$i];
        }

        for ($j = 1; $j <= $key; $j++) {
            $paymentstore[$j] = $updatedPaymentArray[$j];
        }

        /* Agent Array */
        $agentArray = array();
        $agentArray = $sql->fetchAll("tbl_agent", array("ag_status" => 1));

        $this->view->agentArray = $agentArray;
        $this->view->salutation = $salutation;
        $this->view->fname = $fname;
        $this->view->lname = $lname;
        $this->view->email = $email;
        $this->view->zipcode = $zipcode;
        $this->view->address = $address;
        $this->view->state = $state;
        $this->view->city = $city;
        $this->view->phone = $phone;
        $this->view->country = $country;
        $this->view->ag_name = $ag_name;
        $this->view->terms = $terms;
        $this->view->codex = $codex;
        $this->view->drpgateway = $drpgateway;
        $this->view->payment_optn = $payment_option;
        $this->view->drpCardType = $drpCardType;
        $this->view->txtCreditcardno = $txtCreditcardno;
        $this->view->drpExpMonth = $drpExpMonth;
        $this->view->drpExpYear = $expyear;
        $this->view->txtNameoncard = $nameoncard;
        $this->view->txtCvv = $cvv;
        $this->view->ErrorMessage = $errorArray;
        $this->view->paymentstore = $paymentstore;
		$this->view->countryArray = $countryArray;
        $this->view->securityerror = $securityerror;	
        $this->view->render('checkout');
    }

}

